using CoreManager.MessageQueue.Models;
using CoreManager.MessageQueue.Services;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace CoreManager.MessageQueue.Extensions;

/// <summary>
/// 服务集合扩展
/// </summary>
public static class ServiceCollectionExtensions
{
    /// <summary>
    /// 添加Kafka服务
    /// </summary>
    /// <param name="services">服务集合</param>
    /// <param name="configuration">配置</param>
    /// <returns></returns>
    public static IServiceCollection AddKafka(this IServiceCollection services, IConfiguration configuration)
    {
        // 配置选项
        services.Configure<KafkaOptions>(configuration.GetSection(KafkaOptions.SectionName));
        
        // 注册服务
        services.AddSingleton<IKafkaProducerService, KafkaProducerService>();
        services.AddSingleton<IKafkaConsumerService, KafkaConsumerService>();
        
        // 注册后台服务
        services.AddHostedService<KafkaBackgroundService>();
        
        return services;
    }
    
    /// <summary>
    /// 添加Kafka服务
    /// </summary>
    /// <param name="services">服务集合</param>
    /// <param name="configureOptions">配置选项</param>
    /// <returns></returns>
    public static IServiceCollection AddKafka(this IServiceCollection services, Action<KafkaOptions> configureOptions)
    {
        services.Configure(configureOptions);
        
        // 注册服务
        services.AddSingleton<IKafkaProducerService, KafkaProducerService>();
        services.AddSingleton<IKafkaConsumerService, KafkaConsumerService>();
        
        // 注册后台服务
        services.AddHostedService<KafkaBackgroundService>();
        
        return services;
    }
}
